package com.gitee.cui.concurrency.concurrent;

import com.gitee.cui.util.Print;

/**
 * Join等待示例，实现泡茶功能
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/12/9 15:12
 **/
public class JoinDemo {

    private static final int SLEEP_GAP = 500;

    public static String getCurrentThreadName() {
        return Thread.currentThread().getName();
    }

    static class HotWaterThread extends Thread {
        public HotWaterThread() {
            super("** 烧水-Thread");
        }
        @Override
        public void run() {
            try {
                Print.tcfo("洗好水壶");
                Print.tcfo("灌上凉水");
                Print.tcfo("放在火上");
                Thread.sleep(SLEEP_GAP);
                Print.tcfo("水开了");
            } catch (InterruptedException e) {
                Print.tcfo("发生异常被中断");
            }
            Print.tcfo("运行结束");
        }
    }

    static class WashThread extends Thread {

        public WashThread() {
            super("$$ 清洗-Thread");
        }

        @Override
        public void run() {
            try {
                Print.tcfo("洗茶壶");
                Print.tcfo("洗茶杯");
                Print.tcfo("拿茶叶");
                Thread.sleep(SLEEP_GAP);
                Print.tcfo("洗完了");
            } catch (InterruptedException e) {
                Print.tcfo("发生异常被中断");
            }
            Print.tcfo("运行结束");
        }
    }

    public static void main(String[] args) {
        HotWaterThread hThread = new HotWaterThread();
        WashThread wThread = new WashThread();
        hThread.start();
        wThread.start();

        try {
            hThread.join();
            wThread.join();
            Thread.currentThread().setName("主线程");
            Print.tcfo("泡茶喝");
        } catch (InterruptedException e) {
            Print.tcfo(getCurrentThreadName() + "发生异常被中断");
        }
        Print.tcfo(getCurrentThreadName() + "运行结束");
    }
}
